package com.myCommunity.dao.impl;

import java.sql.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import com.myCinema.dao.HibernateUtil;
import com.myCommunity.dao.CommentDao;
import com.myCommunity.entity.Comment;
import com.myCommunity.entity.Users;

public class CommentDaoImpl implements CommentDao {

	public List<Comment> getListByReference(int referenceId,int pageNum,int pageSize) {
		Session sess = null;
		try{
			sess = HibernateUtil.openSession();
			Criteria cri = sess.createCriteria(Comment.class);
			cri.add(Restrictions.eq("referenceId", referenceId));
			if(pageNum>0 && pageSize>0)
				return cri.setFirstResult((pageNum-1)*pageSize).setMaxResults(pageSize).list();
			return cri.list();
		}finally{
			if(sess!=null)
				sess.close();
		}
	}

	public void saveComment(Comment comment) {
		Session sess = null;
		try{
			sess = HibernateUtil.openSession();
			Transaction tx = sess.beginTransaction();
			sess.save(comment);
			tx.commit();
		}finally{
			sess.close();
		}
	}
	
	public static void main(String[] args) {
		Comment c = new Comment(0, ".....", Date.valueOf("2017-02-01"), "109.02.321", 1, 1, 0, 1);
		Session sess = HibernateUtil.openSession();
		Users user = (Users) sess.get(Users.class, 1);
		c.setUser(user);
		new CommentDaoImpl().saveComment(c);
		sess.close();
	}

}
